package com.asiainfo.rt.execution.application;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class MainAppClassLoader extends URLClassLoader {
    private final Class<AppMain> myAppMainClass;

    @SuppressWarnings("deprecation")
    private static URL[] makeUrls() {
        List<URL> classpath = new ArrayList<URL>();
        try {
            String userClassPath = System
                    .getProperty("idea.user.classpath", "");
            StringTokenizer tokenizer = new StringTokenizer(userClassPath,
                    File.pathSeparator, false);
            while (tokenizer.hasMoreTokens()) {
                String pathItem = tokenizer.nextToken();
                classpath.add(new File(pathItem).toURL());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return (URL[]) (URL[]) classpath.toArray(new URL[classpath.size()]);
    }

    public MainAppClassLoader(ClassLoader loader) {
        super(makeUrls(), null);
        this.myAppMainClass = AppMain.class;
    }

    @SuppressWarnings("unchecked")
    protected synchronized Class<AppMain> loadClass(String name, boolean resolve)
            throws ClassNotFoundException {
        if (name.equals(this.myAppMainClass.getName())) {
            return this.myAppMainClass;
        }
        return (Class<AppMain>) super.loadClass(name, resolve);
    }
}